package com.example.emos.wx.user.shiro;

import com.example.emos.wx.user.model.pojo.TbUser;
import com.example.emos.wx.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * OAuth2Realm类实现认证和授权
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/7/27
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserService userService;

    /**
     * 判断传入的AuthenticationToken是否符合要求
     * 也就是是否支持OAuth2Token
     * @param token 传入的AuthenticationToken
     * @return false不支持，true支持
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用）
     *
     * @param principalCollection 权限集合
     * @return 认证信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        认证对象中已经封装了用户信息，所以可以直接得到用户信息
        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
//        获取用户id
        int userId = user.getId();
//        查询用户具备的权限
        Set<String> permsSet = userService.searchUserPermissions(userId);
//        创建授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//       封装权限
        simpleAuthorizationInfo.setStringPermissions(permsSet);
//       返回授权对象
        return simpleAuthorizationInfo;
    }

    /**
     * 认证（验证登录时调用）
     *
     * @param authenticationToken 支持OAuth2Token对象
     * @return 认证信息
     * @throws AuthenticationException 认证信息异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        获取字符串类型的令牌
        String accessToken = (String) authenticationToken.getPrincipal();
//        从临牌字符串中获取Userid
        int userId = jwtUtil.getUserIdFromJwt(accessToken);
//        查询用户信息
        TbUser user = userService.searchById(userId);
//        用户账户是否被冻结
        if(user == null){
            throw new LockedAccountException("该账号已被冻结");
        }
//        向认证对象传入参数,第一个是用户信息，第二个是令牌字符串，第三个是Realm类的名字
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,accessToken,getName());
        return info;
    }
}
